<?php

namespace App\Http\Controllers;

use App\Models\ChannelDateReport;
use App\Models\AuditorDateReport;
use App\Models\User;
use App\Models\CollectorReport;
use App\Models\Setting;
use App\Models\ExtendReport;
use App\Models\ExtendOffline;
use App\Models\UserQzxinyanQuery;
use App\Models\ScoreSetting;
use App\Models\UserScore;
use App\Models\UserReport;
use App\Models\PayAndRepay;
use App\Models\ProductReport;
use App\Models\GeneralReport;
use App\Models\OrderOffline;
use App\Models\Consume;
use App\Models\AdminUser;
use App\Models\DivideOrder;
use App\Models\Mature;
use App\Models\RiskScoreChannel;
use App\Models\RiskScoreConfig;
use App\Models\GlobalConfig;

use App\Models\Order;
use Illuminate\Http\Request;
use GuzzleHttp\Client as GuzzleClient;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\CommonController;
use App\Admin\Controllers\CommonController as AdminCommonController;
use App\Http\Controllers\ProductFlockController;

//use Illuminate\Support\Facades\DB;
class CronController extends Controller
{
    public function getAllTenantId(){
        $adminUser = AdminUser::select('tenant_id')->pluck('tenant_id')->toArray();
        return array_unique($adminUser);
    }

    public function qzxinyan_carrier(Request $request)
    {
        set_time_limit(120);
        $start = date("Y-m-d H:i:s", time() - 3600 * 24 * 120);
        $end = date("Y-m-d H:i:s");
        //echo "$start,$end";
        $datetime = date("Y-m-d H:i:s");
        @file_put_contents('../storage/logs/cron_qzxinyan.log', $datetime . "\n" . "$start,$end" . "\n\n", FILE_APPEND);
        if (!empty($start) && !empty($end)) {
            $rows = UserQzxinyanQuery::where("created_at", '>=', $start)->where("created_at", '<=', $end)->where("token", '<>', '')->where("apiname", '=', 'carrier')->where("state", '=', 0)->get();

            foreach ($rows as $key => $val) {
                $id = $val['id'];
                echo $id;
                $user_id = $val['user_id'];
                $apiname = $val['apiname'];
                $token = $val['token'];
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);
                $apiUser = $member_id;
                $apiKey = $this->xinyanApiKey;
                //apiUser + apiKey + token
                $str = $apiUser . $apiKey;
                $apiEnc = md5($str);
                //echo "$apiUser.$apiKey.$token<br/>";
                $url = "https://qz.xinyan.com/api/user/data?apiUser={$apiUser}&apiEnc={$apiEnc}&token={$token}";
                echo $url;
                @file_put_contents('../storage/logs/cron_qzxinyan.log', "\n" . "$url" . "\n\n", FILE_APPEND);
                $data = file_get_contents($url);
                @file_put_contents("../storage/app/{$apiname}_data_{$user_id}.json", $data);
                //echo ($data);exit();
                $arr = json_decode($data, true);
                //var_dump($arr['detail']['message']);exit("dd");
                if (!empty($arr) && isset($arr['detail']['data']['carrierUserInfo'])) {
                    //$detail = $arr['detail'];

                    $detail['token'] = $arr['detail']['token'];
                    $detail['sourceName'] = $arr['detail']['sourceName'];
                    $detail['sourceDesc'] = $arr['detail']['sourceDesc'];
                    $detail['updateTime'] = $arr['detail']['updateTime'];
                    $detail['dataType'] = $arr['detail']['dataType'];
                    $detail['data']['carrierUserInfo'] = $arr['detail']['data']['carrierUserInfo'];
                    $detail['data']['carrierUserInfo']['point'] = '';
                    if (isset($arr['detail']['data']['bills'][0]['point'])) {
                        $detail['data']['carrierUserInfo']['point'] = $arr['detail']['data']['bills'][0]['point'];
                    }

                    //unset($detail['data']['calls']);
                    //unset($detail['data']['bills']);
                    $val->data = json_encode($detail);
                    //更新报告
                    $userReport = UserReport::where("user_id", $user_id)->where("apiname", $apiname)->first();
                    if (empty($userReport)) {
                        $userReport = new UserReport();
                        $userReport->created_at = date("Y-m-d H:i:s");
                        $userReport->datareport = '';
                        $userReport->user_id = $user_id;
                        $userReport->apiname = $apiname;
                    }
                    $userReport->data = json_encode($detail);
                    $userReport->save();

                }

                $url = "http://qz.xinyan.com/api/user/data/report/json?apiUser={$apiUser}&apiEnc={$apiEnc}&token={$token}";
                echo $url;
                @file_put_contents('../storage/logs/cron_qzxinyan.log', "\n" . "$url" . "\n\n", FILE_APPEND);
                $data = file_get_contents($url);
                @file_put_contents("../storage/app/{$apiname}_datareport_{$user_id}.json", $data);
                $arr = json_decode($data, true);
                //var_dump($arr['detail']['message']);exit("dd");
                if (!empty($arr) && isset($arr['detail'])) {
                    $detail = $arr['detail'];
                    unset($detail['friend_circle']['call_contact_detail']);
                    //echo json_encode($detail);
                    $val->datareport = json_encode($detail);
                    //$val->state = 1;

                    $carrier_ok_key = "carrier_ok_notice";
                    Redis::HSET($carrier_ok_key, $user_id, 1);

                    $val->save();
                    $update = array("carrier_ok" => 1);
                    User::where("id", "=", $user_id)->update($update);
                    //扣手续费

                    //更新报告
                    $userReport = UserReport::where("user_id", $user_id)->where("apiname", $apiname)->first();
                    if (empty($userReport)) {
                        $userReport = new UserReport();
                        $userReport->created_at = date("Y-m-d H:i:s");
                        $userReport->data = '';
                        $userReport->user_id = $user_id;
                        $userReport->apiname = $apiname;
                    }
                    $userReport->datareport = json_encode($detail);
                    $val->state = 1;
                    $val->save();
                    $userReport->save();

                }
            }
        }
    }

    public function qzxinyan_taobaoweb(Request $request)
    {
        set_time_limit(120);
        $start = date("Y-m-d H:i:s", time() - 3600 * 150);
        $end = date("Y-m-d H:i:s");
        //echo "$start,$end";
        $datetime = date("Y-m-d H:i:s");
        @file_put_contents('../storage/logs/qzxinyan_taobao.log', $datetime . "\n" . "$start,$end" . "\n\n", FILE_APPEND);
        if (!empty($start) && !empty($end)) {
            $rows = UserQzxinyanQuery::where("apiname", '=', 'taobaoweb')->where("created_at", '>=', $start)->where("created_at", '<=', $end)->where("token", '<>', '')->where("apiname", '=', 'taobaoweb')->where("state", '=', 0)->get();
            foreach ($rows as $key => $val) {
                $id = $val['id'];
                $user_id = $val['user_id'];
                $apiname = $val['apiname'];
                $token = $val['token'];
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);
                $apiUser = $member_id;
                $apiKey = $this->xinyanApiKey;
                //apiUser + apiKey + token
                $str = $apiUser . $apiKey;
                $apiEnc = md5($str);
                //echo "$apiUser.$apiKey.$token<br/>";
                $url = "https://qz.xinyan.com/api/user/data?apiUser={$apiUser}&apiEnc={$apiEnc}&token={$token}";
                echo $url;
                @file_put_contents('../storage/logs/qzxinyan_taobaoweb.log', "\n" . "$url" . "\n\n", FILE_APPEND);
                $data = file_get_contents($url);
                echo $data;
                @file_put_contents("../storage/app/{$apiname}_{$user_id}.json", $data);
                $arr = json_decode($data, true);
                //dd($arr);
                if (!empty($arr)) {
                    $detail = $arr['detail'];
                    $val->datareport = json_encode($detail);

                    $update = array("taobaoweb_ok" => 1);
                    User::where("id", "=", $user_id)->update($update);
                    //更新报告
                    $userReport = UserReport::where("user_id", $user_id)->where("apiname", $apiname)->first();
                    if (empty($userReport)) {
                        $userReport = new UserReport();
                        $userReport->created_at = date("Y-m-d H:i:s");
                        $userReport->data = '';
                        $userReport->user_id = $user_id;
                        $userReport->apiname = $apiname;
                    }
                    $userReport->datareport = json_encode($detail);
                    $userReport->save();

                    $val->state = 1;
                    $val->save();
                }
            }
        }
    }

    //用户审核
    public function user_verify(Request $request)
    {

        $start = date("Y-m-d H:i:s", time() - 3600 * 24 * 100);
        $end = date("Y-m-d H:i:s");
        echo "$start,<br/>";
        $datetime = date("Y-m-d H:i:s");
        @file_put_contents('../storage/logs/cron_postconvert.log', $datetime . "\n" . "$start,$end" . "\n\n", FILE_APPEND);
        $scoreSetting = ScoreSetting::get();
        //dd($scoreSetting);
        if (!empty($start) && !empty($end) && !empty($scoreSetting)) {
            $where = array(
                'idcard_ok' => 1,
                'alive_ok' => 1,
                'bankcard_ok' => 1,
                'emergency_contact_ok' => 1,
                'company_ok' => 1,
                'carrier_ok' => 1,
                'taobaoweb_ok' => 1,
            );
            $users = User::where("created_at", '>=', $start)->where("created_at", '<=', $end)->where($where)->where("convert", '=', 0)->get();

            foreach ($users as $key => $val) {
                $user_id = $val['id'];
                $this->radar($val);//通过新颜接口获取-多头报告
                echo "$user_id,";
                $score = 0;
                //UserScore
                $idcard_ok = $val->idcard_ok;
                $alive_ok = $val->alive_ok;
                $bankcard_ok = $val->bankcard_ok;
                $sesamecredit_ok = $val->sesamecredit_ok;
                $emergency_contact_ok = $val->emergency_contact_ok;
                $company_ok = $val->company_ok;
                foreach ($scoreSetting as $_key => $_val) {
                    $setting_id = $_val->id;
                    $keyname = $_val->name;
                    $keybrief = $_val->brief;
                    $keyscore = $_val->value;

                    //更新用户所得分数
                    $userScore = UserScore::where("user_id", "=", $user_id)->where("setting_id", "=", $setting_id)->first();
                    if (empty($userScore)) {
                        $userScore = new UserScore();
                    }
                    $userScore->setting_id = $setting_id;
                    $userScore->user_id = $user_id;
                    $userScore->name = $keyname;
                    $userScore->brief = $keybrief;
                    $userScore->score = 0;
                    if ($keyname == 'alive' && $alive_ok == 1) { //活体检测
                        $userScore->score = $keyscore;
                        $score += $keyscore;
                    } elseif ($keyname == 'idcard' && $idcard_ok == 1) { //实名认证
                        $userScore->score = $keyscore;
                        $score += $keyscore;
                    } elseif ($keyname == 'userinfo' && $emergency_contact_ok == 1 && $company_ok == 1) { //紧急联系人、单位信息、住址
                        $userScore->score = $keyscore;
                        $score += $keyscore;
                    } elseif ($keyname == 'carrier_open_months_between_6_24') { //	手机入网时间大于6个月小于24个月5分
                        $userScore->score = $keyscore;
                        $score += $keyscore;
                    }
                    $userScore->save();

                }

                $val->score = $score;
                $val->convert = 1;
                $val->save();

                if ($idcard_ok == 1 && $alive_ok == 1 && $bankcard_ok == 1 && $sesamecredit_ok == 1 && $emergency_contact_ok == 1) {

                }
            }
        }
    }

    /**
     * @param
     * @return mixed
     *  新颜-全景雷达
     */
    public function radar($user)
    {
        $return['code'] = -1;
        $return['text'] = '';
        if (!empty($user)) {
            //$user = User::select("id",'mobile','verify_name','verify_idcard_no','verify_bankcard_no')->where("id","=",$uid)->first();

            if (!empty($user)) {
                $uid = $user->id;
                $verify_idcard_no = $user->verify_idcard_no;
                $verify_bankcard_no = $user->verify_bankcard_no;
                $mobile = $user->mobile;
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require($path);
                $trans_id = BaofooUtils::create_uuid();//商户订单号
                $trade_date = BaofooUtils::trade_date();//交易时间

                $request_url = 'https://api.xinyan.com/product/radar/v3/report';

                $arrayData = array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "trans_id" => $trans_id,
                    "trade_date" => $trade_date,
                    "id_no" => $verify_idcard_no,
                    "id_name" => $user->verify_name,
                    "bankcard_no" => $verify_bankcard_no,
                    "phone_no" => $mobile,
                    "industry_type" => "A1", //根据当前商户的行业类型传参数
                    //"versions" => '	1.3.0'

                );
                // *** 数据格式化***
                $data_content = "";
                //==================转换数据类型=============================================
                if ($data_type == "json") {
                    $data_content = str_replace("\\/", "/", json_encode($arrayData));//转JSON
                }
                // **** 先BASE64进行编码再RSA加密 ***
                $BFRsa = new BFRSA($pfxpath, $cerpath, $pfx_pwd, TRUE); //实例化加密类。
                $data_content = $BFRsa->encryptedByPrivateKey($data_content);
                Log::LogWirte("====加密串" . $data_content);
                /**============== http 请求==================== **/
                $PostArry = array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "data_type" => $data_type,
                    "data_content" => $data_content);
                @file_put_contents('../storage/logs/radar.log', $request_url . "\n" . json_encode($arrayData) . "\n", FILE_APPEND);
                $reslut = HttpClient::Post($PostArry, $request_url);  //发送请求到服务器，并输出返回结果。
                @file_put_contents('../storage/logs/radar.log', "\nRES：" . $reslut . "\n\n", FILE_APPEND);
                //exit($reslut);
                $arr = json_decode($reslut, true);
                if (isset($arr['success'])) {
                    if ($arr['success'] == true) {
                        if (isset($arr['data'])) {
                            $return['code'] = 0;
                            $return['text'] = '成功';
                            $apiName = 'radar';
                            $userQzxinyanQuery = new UserQzxinyanQuery();
                            $userQzxinyanQuery->user_id = $uid;
                            $userQzxinyanQuery->apiname = $apiName;
                            $userQzxinyanQuery->taskid = '';
                            $userQzxinyanQuery->url = '';
                            $userQzxinyanQuery->datareport = json_encode($arr['data']);
                            $userQzxinyanQuery->data = '';
                            $userQzxinyanQuery->created_at = date("Y-m-d H:i:s");
                            $userQzxinyanQuery->save();

                            //更新报告
                            $userReport = UserReport::where("user_id", $uid)->where("apiname", $apiName)->first();
                            if (empty($userReport)) {
                                $userReport = new UserReport();
                                $userReport->user_id = $uid;
                                $userReport->apiname = $apiName;
                                $userReport->data = '';
                            }
                            $userReport->datareport = json_encode($arr['data']);
                            $userReport->save();
                        } else {
                            $return['text'] = $arr['data']['desc'];
                        }

                    } else {
                        $return['text'] = $arr['errorMsg'];
                    }
                }
            }
        }
        return $return;
    }

    //审核订单
    public function checkOrders(Request $request)
    {
        $return['code'] = 0;
        $return['text'] = '';
        $start = date("Y-m-d H:i:s", time() - 3600 * 48);
        $end = date("Y-m-d H:i:s");
        if (!empty($start) && !empty($end)) {
            $orders = Order::where("created_at", '>=', $start)->where("created_at", '<=', $end)->where("state", '=', 0)->where("handle", '=', 0)->get();
            foreach ($orders as $key => $val) {
                $user_state = $val->user->state;
                $verify_name = $val->user->verify_name;
                $verify_bankcard_no = $val->user->verify_bankcard_no;
                $fuiou_protocol_no = $val->user->fuiou_protocol_no;
                $score = $val->user->score;
                $state = $val->user->state;
                $user_id = $val->user_id;
                $created_at = $val->created_at;
                $total_fee = $val->total_fee;
                $change_fee = $val->change_fee;
                $real_fee = $val->real_fee;
                $_order = array(
                    'user_id' => $user_id,
                    'verify_name' => $verify_name,
                    'verify_bankcard_no' => $verify_bankcard_no,
                    'score' => $score,
                    'total_fee' => $total_fee,
                    'change_fee' => $change_fee,
                    'real_fee' => $real_fee,
                    'created_at' => date("Y-m-d H:i:s", strtotime($created_at)),
                );
                if (!empty($user_id) && !empty($verify_name) && !empty($verify_bankcard_no) && !empty($fuiou_protocol_no) && $state > 0) {
                    //$val->state = 1;
                    $val->handle = 1;
                    $val->audited_at = date("Y-m-d H:i:s");
                    $val->save();
                    $return['success'][] = $_order;
                } else {
                    if ($user_state < 0) {
                        $val->state = -1;
                        $val->handle = 1;
                        $val->save();
                    }
                    $return['fail'][] = $_order;
                }
            }
        }
        return $return;
    }

    //处理催收订单
    public function checkRepayOrders(Request $request)
    {
        $return['code'] = 0;
        $return['text'] = '';
        $start = date("Y-m-d H:i:s", time() - 3600 * 48);
        $end = date("Y-m-d H:i:s");
        if (!empty($start) && !empty($end)) {
            $orders = Order::where("repayment_at", '>=', $start)->where("repayment_at", '<=', $end)->where("state", '=', 2)->where("repayment_state", '=', 0)->get();

            foreach ($orders as $key => $val) {
                $repayment_at = $val->repayment_at;
                if (strtotime($repayment_at) < time()) {
                    $val->repayment_state = 1;
                    $val->save();
                }
            }
        }
        return $return;
    }

    //推广数据
    public function channelReport(Request $request)
    {
        try{
            $date = date("Y-m-d");
    //        $date = date("Y-m-d", strtotime('-7 day'));
            $starttime = $date . " 00:00:00";
            $endtime = $date . ' 23:59:59';
            if (!empty($starttime) && !empty($endtime)) {
                //获取所有的teannt_id
                $allTenantId = $this->getAllTenantId();
                if(!count($allTenantId)) die;

                foreach ($allTenantId as $tenval){
                    //注册人数
                    $channelOrderData = array();
                    $users = User::withoutGlobalScopes()->where('tenant_id', $tenval)->select("mastuer", "id", "channel_id", "idcard_ok", 'alive_ok', 'bankcard_ok', 'carrier_ok', 'verify_pay_ok' , 'emergency_contact_ok')->where("created_at", '>=', $starttime)->where("created_at", '<=', $endtime)->get();
                    foreach ($users as $key => $val) {
                        $channel_id = $val->channel_id;
                        $idcard_ok = $val->idcard_ok;
                        $verify_pay_ok = $val->verify_pay_ok;
                        $carrier_ok = $val->carrier_ok;
                        $mastuer = $val->mastuer;
                        $emergency_contact_ok = $val->emergency_contact_ok;
                        if ($channel_id > 0) {
                            if (!isset($channelOrderData[$channel_id])) {
                                $channelOrderData[$channel_id]['user_count'] = 0;
                                $channelOrderData[$channel_id]['user_idcard_ok_count'] = 0;
                                $channelOrderData[$channel_id]['abnormal'] = 0;
                            }
                            $channelOrderData[$channel_id]['user_count']++;
                            if ($idcard_ok == 1 && $verify_pay_ok == 1 && $carrier_ok == 1 && $emergency_contact_ok == 1) {
                                $channelOrderData[$channel_id]['user_idcard_ok_count']++;
                            }
                            if ($mastuer > 0) {
                                $channelOrderData[$channel_id]['abnormal']++;
                            }
                        }
                    }

                    //首签人数
                    $first_orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->where('borrow_count', '=', 0)->where("confirm_date", [$starttime, $endtime])->get()->toArray();
                    foreach ($first_orders as $key => $val) {
                        $channel_id = $val['channel_id'];
                        if (!isset($channelOrderData[$channel_id]['first_borrow'])) {
                            $channelOrderData[$channel_id]['first_borrow'] = 0;
                        }

                        if (!isset($channelOrderData[$channel_id]['first_borrow_money'])) {
                            $channelOrderData[$channel_id]['first_borrow_money'] = 0;
                        }
                        $channelOrderData[$channel_id]['first_borrow']++;
                        $channelOrderData[$channel_id]['first_borrow_money'] += $val['real_fee'];
                    }

                    //复签人数
                    $reborrow_orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->where('borrow_count', '>', 0)->where("confirm_date", [$starttime, $endtime])->get()->toArray();
                    foreach ($reborrow_orders as $key => $val) {
                        $channel_id = $val['channel_id'];
                        if (!isset($channelOrderData[$channel_id]['reborrow'])) {
                            $channelOrderData[$channel_id]['reborrow'] = 0;
                        }
                        if (!isset($channelOrderData[$channel_id]['reborrow_money'])) {
                            $channelOrderData[$channel_id]['reborrow_money'] = 0;
                        }
                        $channelOrderData[$channel_id]['reborrow']++;
                        $channelOrderData[$channel_id]['reborrow_money'] += $val['real_fee'];
                    }

                    //申请人数
                    $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select("id", "channel_id", "state", 'user_id')->where("created_at", '>=', $starttime)->where("created_at", '<=', $endtime)->get()->toArray();
                    $orders = $this->assoc_unique($orders, 'user_id');

                    foreach ($orders as $key => $val) {
                        $channel_id = $val['channel_id'];
                        if ($channel_id > 0) {
                            if (!isset($channelOrderData[$channel_id]['order_count'])) {
                                $channelOrderData[$channel_id]['order_count'] = 0;
                            }
                            $channelOrderData[$channel_id]['order_count']++;
                        }
                    }

                    //放款金额和放款笔数
                    $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->where("confirm_date", [$starttime, $endtime])->get()->toArray();
                    foreach ($orders as $key => $val) {
                        $channel_id = $val['channel_id'];

                        if (!isset($channelOrderData[$channel_id]['order_today_paycount'])) {
                            $channelOrderData[$channel_id]['order_today_paycount'] = 0;
                        }
                        $channelOrderData[$channel_id]['order_today_paycount']++;//放款笔数

                        if (!isset($channelOrderData[$channel_id]['order_payment'])) {
                            $channelOrderData[$channel_id]['order_payment'] = 0;
                        }
                        $channelOrderData[$channel_id]['order_payment'] += $val['real_fee'];//放款金额
                    }

                    if (!empty($channelOrderData)) {
                        foreach ($channelOrderData as $channel_id => $val) {
                            $channelDateReport = ChannelDateReport::withoutGlobalScopes()->where('tenant_id', $tenval)->where("date", $date)->where("channel_id", $channel_id)->first();
                            if (!count($channelDateReport)) {
                                $channelDateReport = new ChannelDateReport();
                                $channelDateReport->channel_id = $channel_id;
                                $channelDateReport->tenant_id = $tenval;
                                $channelDateReport->date = $date;
                            }
                            $channelDateReport->user_count = $val['user_count'] ?? 0;//注册人数
                            $channelDateReport->user_idcard_ok_count = $val['user_idcard_ok_count'] ?? 0;//认证通过人数
                            $channelDateReport->first_borrow = $val['first_borrow'] ?? 0;//首借人数
                            $channelDateReport->first_borrow_money = $val['first_borrow_money'] ?? 0;//首借金额
                            $channelDateReport->reborrow = $val['reborrow'] ?? 0;//复借人数
                            $channelDateReport->reborrow_money = $val['reborrow_money'] ?? 0;//复借金额
                            $channelDateReport->order_count = $val['order_count'] ?? 0;//申请人数
                            $channelDateReport->order_payment = $val['order_payment'] ?? 0;//放款金额
                            $channelDateReport->order_today_paycount = $val['order_today_paycount'] ?? 0;//放款笔数
                            $channelDateReport->abnormal = $val['abnormal'] ?? 0;//非正常用户数统计

                            $channelDateReport->save();
                        }
                    }

                    //查询100天内的回款笔数和回款金额
                    $meonthAgo = date('Y-m-d H:i:s', time() - 86400 * 100);
                    $orderOfflneRepayArr = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->whereNotIn('method', ['免减'])->where('created_at', '>=', $meonthAgo)->get();//回款的订单id
                    $extendOfflineRepayArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->where('created_at', '>=', $meonthAgo)->get();//展期的订单ids

                    $repay_order_ids = [];
                    foreach ($orderOfflneRepayArr as $key => $orval){
                        array_push($repay_order_ids, $orval->order_id);
                    }

                    foreach ($extendOfflineRepayArr as $key => $exval){
                        array_push($repay_order_ids, $exval->order_id);
                    }

                    $channelRepaymentData = [];
                    $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->with(['orderoffline' => function($query){
                        $query->withoutGlobalScopes();
                    }, 'extendoffline' => function($query){
                        $query->withoutGlobalScopes();
                    }])->whereIn('id', $repay_order_ids)->where('borrow_count', 0)->get();
                    if(count($orders)){
                        $channelRepaymentData = [];
                        foreach ($orders as $key => $val) {
                            if(!$val['payment_at']) continue;

                            $channel_id = $val['channel_id'];
                            $payment_at = substr($val['payment_at'], 0, 10);

                            if (!isset($channelRepaymentData[$channel_id][$payment_at]['order_repay_mon'])) {
                                $channelRepaymentData[$channel_id][$payment_at]['order_repay_mon'] = 0;
                            }

                            if (!isset($channelRepaymentData[$channel_id][$payment_at]['order_repay_count'])) {
                                $channelRepaymentData[$channel_id][$payment_at]['order_repay_count'] = 0;
                            }
                            //统计所有此订单下的还款笔数和还款总金额
                            $this_repay_money = 0;
                            if (count($val->orderoffline) && !count($val->extendoffline)) {//展期为空，扣款不为空
                                foreach ($val->orderoffline as $order_key => $order_val) {
                                    if ($order_val['method'] != '免减') {
                                        $this_repay_money += $order_val['money'];
                                    }
                                }
                            }

                            //统计所有此订单下的展期笔数和展期总金
                            if (count($val->extendoffline)) {
                                foreach ($val->extendoffline as $extend_key => $extend_val) {
                                    if($extend_key == 0){//只统计第一次展期的费用，多次展期算复借
                                        $this_repay_money += $extend_val['money'];
                                    }
                                }
                            }

                            $channelRepaymentData[$channel_id][$payment_at]['order_repay_count'] ++;

                            $channelRepaymentData[$channel_id][$payment_at]['order_repay_mon'] += $this_repay_money;//回款金额
                        }
                    }

                    //放款那一天的回款率和回款金额以及回款笔数数
                    if(count($channelRepaymentData)){
                        foreach ($channelRepaymentData as $channel_id => $pay_val) {
                            foreach ($pay_val as $payment_at => $repay) {
                                $channel_data_report = ChannelDateReport::withoutGlobalScopes()->where('tenant_id', $tenval)->where("date", $payment_at)->where("channel_id", $channel_id)->first();
                                if (!count($channel_data_report)) {
                                    $channel_data_report = new ChannelDateReport();
                                    $channel_data_report->channel_id = $channel_id;
                                    $channel_data_report->date = $payment_at;
                                    $channel_data_report->tenant_id = $tenval;
                                }
                                $channel_data_report->order_repay_count = $repay['order_repay_count'];
                                $channel_data_report->order_repay_mon = $repay['order_repay_mon'];
                                $channel_data_report->order_repay_rate = 0;
                                if ($channel_data_report->first_borrow) {//回款率
                                    $channel_data_report->order_repay_rate = round($repay['order_repay_count'] / $channel_data_report->first_borrow, 2);
                                }
                                $channel_data_report->save();
                            }
                        }
                    }

                    if (count($channelOrderData)) {
                        foreach ($channelOrderData as $channel_id => $val) {
                            $channelDateReport = ChannelDateReport::withoutGlobalScopes()->where('tenant_id', $tenval)->where("date", $date)->where("channel_id", $channel_id)->first();
                            if (!count($channelDateReport)) {
                                $channelDateReport = new ChannelDateReport();
                                $channelDateReport->channel_id = $channel_id;
                                $channelDateReport->created_at = date("Y-m-d H:i:s");
                                $channelDateReport->tenant_id = $tenval;
                                $channelDateReport->date = $date;
                            }

                            $channelDateReport->order_payed_rate = 0;//下款率
                            if (!empty($channelDateReport->user_count)) {//放款率 当日注册用户的首借放款人数/当日注册人数
                                $channelDateReport->order_payed_rate = round($channelDateReport->first_borrow / $channelDateReport->user_count, 2);
                                $channelDateReport->save();
                            }
                        }
                    }
                }
            }
        }catch (\Exception $ex){
            @file_put_contents('../storage/report/channel_report_error_'.date('Ymd').'.log', date('Y-m-d H:i:s').'_'.$ex->getMessage().$ex->getLine().$ex->getCode().PHP_EOL, FILE_APPEND);

            echo $ex->getMessage();
        }
        echo 'success';
    }

    //获取UV的统计数据
    protected function getUvStastic()
    {
        $send_url = env('RISKDECISION') . '/easyuseapi/user/track/countvisitor';
        $params = [
            'query' => [
                'serverid' => env('BSIGN'),
                'days' => 3
            ],
            'headers' => [
                'ident' => 'production'
            ]
        ];
        try {
            $response = $this->guzzle_get($send_url, $params);
            $result = json_decode($response->getBody()->getContents(), true);
            file_put_contents('../storage/logs/get_uv_stastic_' . date('Ym') . '.log', json_encode($result) . "||" . date('Y-m-d H:i:s') . '||' . json_encode($params) . PHP_EOL, FILE_APPEND);
        } catch (\Exception $ex) {
            file_put_contents('../storage/logs/get_uv_stastic_error_' . date('Ym') . '.log', $ex->getMessage() . date('Y-m-d H:i:s') . json_encode($params) . PHP_EOL, FILE_APPEND);
        }
        return $result;
    }

    //签约统计
    public function auditorReport(Request $request)
    {
        $date = trim($request->input('date', ''));
        if (empty($date)) {
            $date = date("Y-m-d", strtotime("-1 day"));
        }
        $starttime = $date . " 00:00:00";
        $endtime = $date . ' 23:59:59';
        echo "$starttime,$endtime";
        if (!empty($starttime) && !empty($endtime)) {
            //获取所有的teannt_id
            $allTenantId = $this->getAllTenantId();
            if(!count($allTenantId)) die;

            foreach ($allTenantId as $tenval){
                $reportData = array();
                //审核订单数
                $users = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select("id", 'auditor_id', 'state')->where("audited_at", '>=', $starttime)->where("audited_at", '<=', $endtime)->get();

                foreach ($users as $key => $val) {
                    $auditor_id = $val->auditor_id;
                    $state = $val->state;
                    if ($auditor_id > 0) {
                        if (!isset($reportData[$auditor_id])) {
                            $reportData[$auditor_id]['user_count'] = 0;
                            $reportData[$auditor_id]['user_pass_count'] = 0;
                        }
                        $reportData[$auditor_id]['user_count']++;
                        if ($state == 2) {
                            $reportData[$auditor_id]['user_pass_count']++;
                        }

                    }
                }
    //            var_dump($reportData);

                if (!empty($reportData)) {
                    foreach ($reportData as $auditor_id => $val) {
                        $auditorDateReport = AuditorDateReport::where('tenant_id', $tenval)->where("auditor_id", $auditor_id)->where("date", $date)->first();
                        if (empty($auditorDateReport)) {
                            $auditorDateReport = new AuditorDateReport();
                            $auditorDateReport->auditor_id = $auditor_id;
                            $auditorDateReport->created_at = date("Y-m-d H:i:s");
                            $auditorDateReport->tenant_id = $tenval;
                        }
                        $auditorDateReport->date = $date;
                        $auditorDateReport->user_count = $val['user_count'];
                        $auditorDateReport->user_pass_count = $val['user_pass_count'];
                        $auditorDateReport->save();
                    }
                }


                $reportData = array();
                $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select("id", "channel_id", 'auditor_id', "state", 'created_at', 'real_fee', 'repayment_fee')->where("created_at", '>=', $starttime)->where("created_at", '<=', $endtime)->get();
                //dd($orders);
                foreach ($orders as $key => $val) {
                    $auditor_id = $val->auditor_id;
                    $state = $val->state;
                    if ($auditor_id > 0) {
                        if (!isset($reportData[$auditor_id]['order_count'])) {
                            $reportData[$auditor_id]['order_count'] = 0;
                        }
                        $reportData[$auditor_id]['order_count']++;

                        if (!isset($reportData[$auditor_id]['order_payed_count'])) {
                            $reportData[$auditor_id]['order_payed_count'] = 0;
                        }
                        if (!isset($reportData[$auditor_id]['order_payed_cash'])) {
                            $reportData[$auditor_id]['order_payed_cash'] = 0;
                        }
                        if ($state == 2) {
                            $reportData[$auditor_id]['order_payed_count']++;//放款数
                            $reportData[$auditor_id]['order_payed_cash'] += $val->real_fee;
                        }
                        if (!isset($reportData[$auditor_id]['user_notpass_count'])) {
                            $reportData[$auditor_id]['user_notpass_count'] = 0;
                        }
                        if ($state == -1) {
                            $reportData[$auditor_id]['user_notpass_count']++;//审核不通过数
                        }
                    }
                }

                if (!empty($reportData)) {
                    foreach ($reportData as $auditor_id => $val) {
                        $auditorDateReport = AuditorDateReport::where('tenant_id', $tenval)->where("auditor_id", $auditor_id)->where("date", $date)->first();
                        if (empty($auditorDateReport)) {
                            $auditorDateReport = new AuditorDateReport();
                            $auditorDateReport->auditor_id = $auditor_id;
                            $auditorDateReport->created_at = date("Y-m-d H:i:s");
                            $auditorDateReport->tenant_id = $tenval;
                        }
                        $auditorDateReport->date = $date;
                        $auditorDateReport->order_count = $val['order_count'];//审请数
                        $auditorDateReport->order_payed_count = $val['order_payed_count'];//放款数
                        $auditorDateReport->order_payed_cash = $val['order_payed_cash'];//放款金额
                        $auditorDateReport->user_notpass_count = $val['user_notpass_count'];//不通过数
                        $auditorDateReport->order_payed_rate = 0;
                        if (!empty($val['user_count'])) {
                            $auditorDateReport->order_payed_rate = round($val['order_payed_count'] / $val['user_count'], 2);//放款率
                        }
                        $auditorDateReport->save();
                    }
                }
                //回款金额，回款率，回款人数
                $meonthAgo = date('Y-m-d H:i:s', time() - 86400 * 100);
                $orderOfflneRepayArr = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->whereNotIn('method', ['免减'])->where('created_at', '>=', $meonthAgo)->get();//回款的订单id
                $extendOfflineRepayArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->where('created_at', '>=', $meonthAgo)->get();//展期的订单ids
                $repay_order_ids = [];
                foreach ($orderOfflneRepayArr as $key => $orval){
                    array_push($repay_order_ids, $orval->order_id);
                }
                foreach ($extendOfflineRepayArr as $key => $exval){
                    array_push($repay_order_ids, $exval->order_id);
                }
                $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->with('orderoffline', 'extendoffline')->select('user_id', 'auditor_id', 'created_at','extend_time','finished_at',"id", "days" , "channel_id", "state", 'payment_at', 'total_fee', 'real_fee', 'repayment_fee', 'user_id', 'borrow_count')->whereIn('id', $repay_order_ids)->get();

                $auditorRepaymentData = [];
                $auditorUserIds = [];
                foreach ($orders as $key => $val) {

                    $auditor_id = $val['auditor_id'];
                    $payment_at = substr($val['payment_at'], 0, 10);
                    $user_id = $val['user_id'];

                    if (!isset($auditorRepaymentData[$auditor_id][$payment_at]['order_repay_mon'])) {
                        $auditorRepaymentData[$auditor_id][$payment_at]['order_repay_mon'] = 0;
                    }

                    if (!isset($auditorRepaymentData[$auditor_id][$payment_at]['order_repay_count'])) {
                        $auditorRepaymentData[$auditor_id][$payment_at]['order_repay_count'] = 0;
                    }
                    //统计所有此订单下的还款笔数和还款总金额
                    $this_repay_money = 0;
                    if (count($val->orderoffline)) {
                        foreach ($val->orderoffline as $order_key => $order_val) {
                            if ($order_val['method'] != '免减') {
                                $this_repay_money += $order_val['money'];
                            }
                        }
                    }

                    //统计所有此订单下的展期笔数和展期总金
                    if (count($val->extendoffline)) {
                        foreach ($val->extendoffline as $extend_key => $extend_val) {
                            $this_repay_money += $extend_val['money'];
                        }
                    }

                    if(!in_array($user_id, $auditorUserIds)){
                        array_push($auditorUserIds, $user_id);
                        $auditorRepaymentData[$auditor_id][$payment_at]['order_repay_count'] ++;//回款人数
                    }

                    $auditorRepaymentData[$auditor_id][$payment_at]['order_repay_mon'] += $this_repay_money;//回款金额
                }

                //放款那一天的回款率和回款金额以及回款笔数数
                if(count($auditorRepaymentData)){
                    foreach ($auditorRepaymentData as $auditor_id => $pay_val) {
                        foreach ($pay_val as $payment_at => $repay) {
                            $auditor_data_report = AuditorDateReport::where('tenant_id', $tenval)->where("date", $payment_at)->where("auditor_id", $auditor_id)->first();
                            if (!count($auditor_data_report)) {
                                $auditor_data_report = new AuditorDateReport();
                                $auditor_data_report->auditor_id = $auditor_id;
                                $auditor_data_report->created_at = date("Y-m-d H:i:s");
                                $auditor_data_report->date = $payment_at;
                                $auditor_data_report->tenant_id = $tenval;
                            }
                            $auditor_data_report->order_repayed_count = $repay['order_repay_count'];
                            $auditor_data_report->order_repayed_cash = $repay['order_repay_mon'];
                            $auditor_data_report->order_repayed_rate = 0;
                            if ($auditor_data_report->order_repayed_cash + $auditor_data_report->order_payed_cash) {//回款率
                                $auditor_data_report->order_repayed_rate = round($auditor_data_report->order_repayed_cash / ($auditor_data_report->order_repayed_cash + $auditor_data_report->order_payed_cash), 2);
                            }
                            $auditor_data_report->save();
                        }
                    }
                }
            }
        }
        echo 'success';
    }

    //签约金额和履约金额
    public function payAndRepay(request $request)
    {
        $date = date("Y-m-d", time());
//        $date = date("Y-m-d", strtotime('-2 day'));

        $today = $date . " 00:00:00";
        $todayEnd = $date . ' 23:59:59';

        //获取所有的teannt_id
        $allTenantId = $this->getAllTenantId();
        if(!count($allTenantId)) die;

        foreach ($allTenantId as $tenval){
            //================回款统计======================
            $allNatialRepayMon = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->whereNotIn('method', ['免减'])->whereBetween('created_at', [$today, $todayEnd])->get();//回款金额
            $allNatialExtendMon = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id')->whereBetween('created_at', [$today, $todayEnd])->get();//展期的金额
            $allRepayOrderIds = [];
            foreach ($allNatialRepayMon as $key => $val) {
                if (!in_array($val->order_id, $allRepayOrderIds)) {
                    array_push($allRepayOrderIds, $val->order_id);
                }
            }
            foreach ($allNatialExtendMon as $key => $val) {
                if (!in_array($val->order_id, $allRepayOrderIds)) {
                    array_push($allRepayOrderIds, $val->order_id);
                }
            }

            $home['todayRepayPeople'] = 0;
            $payedMonOrders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) today_repay_people')->whereIn('id', $allRepayOrderIds)->first();
            if ($payedMonOrders['today_repay_people']) {
                $home['todayRepayPeople'] = $payedMonOrders['today_repay_people'];//回款人数
            }

            //回款金额
            $home['today_repay_arr'] = 0;
            $todayRepayArr = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) today_repay_fee')->whereNotIn('method', ['免减'])->where('created_at', '>=', $today)->first();//回款金额
            $extendArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) today_extendarr')->where('created_at', '>=', $today)->first();//今日展期的金额
            if ($todayRepayArr['today_repay_fee'] + $extendArr['today_extendarr']) {
                $home['today_repay_arr'] = $todayRepayArr['today_repay_fee'] + $extendArr['today_extendarr'];
            }

            //支付回款，微信回款
            $todayRepayArr = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('method', 'money')->whereIn('method', ['线下支付宝', '线下微信'])->where('created_at', '>=', $today)->get();//回款金额
            $extendArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('method', 'money')->whereIn('method', ['线下支付宝', '线下微信'])->where('created_at', '>=', $today)->get();//今日展期的金额
            $zhifubao = 0;
            $weixin = 0;
            foreach ($todayRepayArr as $akey => $aval) {
                if ($aval->method == '线下支付宝') {
                    $zhifubao += $aval->money;
                }
                if ($aval->method == '线下微信') {
                    $weixin += $aval->money;
                }
            }
            foreach ($extendArr as $bkey => $bval) {
                if ($bval->method == '线下支付宝') {
                    $zhifubao += $bval->money;
                }
                if ($bval->method == '线下微信') {
                    $weixin += $bval->money;
                }
            }
            //线下回款
            $home['offline_repay'] = $weixin + $zhifubao;
            //在线回款
            $home['online_repay'] = $home['today_repay_arr'] - $home['offline_repay'];
            //展期人数
            $extendOrderIds = [];
            foreach ($allNatialExtendMon as $alkey => $alval) {
                if (!in_array($alval->order_id, $extendOrderIds)) {
                    array_push($extendOrderIds, $alval->order_id);
                }
            }
            $home['extend_count'] = 0;
            $payedExtendMonOrders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) today_extend_repay_people')->whereIn('id', $extendOrderIds)->first();
            if ($payedExtendMonOrders['today_extend_repay_people']) {
                $home['extend_count'] = $payedExtendMonOrders['today_extend_repay_people'];//展期回款人数
            }
            //展期回款金额
            $home['extend_mon'] = 0;
            $todayExtendArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) today_extend_arr')->where('created_at', '>=', $today)->first();//今日展期的金额
            if ($todayExtendArr['today_extend_arr']) {
                $home['extend_mon'] = $todayExtendArr['today_extend_arr'];
            }
            //期内还款
            $orderIds = [];
            $home['repay_ontime'] = 0;//期内还款人数
            $home['repay_ontime_mon'] = 0;//期内还款金额
            $orderoffline_obj = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id', 'money')->whereBetween('created_at', [$today, $todayEnd])->whereNotIn('method', ['免减'])->get();//获取今日还款的数据
            foreach ($orderoffline_obj as $onkey => $onval){
                array_push($orderIds, $onval->order_id);
                $home['repay_ontime_mon'] += $onval->money;//期内还款金额
            }
            $extend_obj = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id', 'money')->whereBetween('created_at', [$today, $todayEnd])->get();
            foreach ($extend_obj as $exkey => $exval){
                array_push($orderIds, $exval->order_id);
                $home['repay_ontime_mon'] += $exval->money;//期内还款金额
            }
            $repayOntimeOrders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) repay_ontime_people')->whereIn('id', $orderIds)->first();
            if ($repayOntimeOrders['repay_ontime_people']) {
                $home['repay_ontime'] = $repayOntimeOrders['repay_ontime_people'];//期内还款人数
            }
            //催收回款
            $home['collect_count'] = 0;
            $home['collect_mon'] = 0;
            $collect_count = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) collector_count')->whereIn('id', $orderIds)->where('collector_id', '>', 0)->first();
            if($collect_count['collector_count']){
                $home['collect_count'] = $collect_count['collector_count'];//催收还款人数
            }

            $collector_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereIn('id', $orderIds)->where('collector_id', '>', 0)->get();
            $collectorIds = [];
            foreach ($collector_obj as $cokey => $coval){
                array_push($collectorIds, $coval->id);//获得还款并且催收的订单id
            }
            //查询催收还款金额
            $orderoffline_colobj = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id', 'money')->whereIn('order_id', $collectorIds)->whereBetween('created_at', [$today, $todayEnd])->whereNotIn('method', ['免减'])->get();//获取今日还款的数据
            foreach ($orderoffline_colobj as $cuikey => $cuival){
                $home['collect_mon'] += $cuival->money;//期内还款金额
            }
            $extend_colobj = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->select('order_id', 'money')->whereIn('order_id', $collectorIds)->whereBetween('created_at', [$today, $todayEnd])->get();//获取今日还款的数据
            foreach ($extend_colobj as $cuiexkey => $cuiexval){
                $home['collect_mon'] += $cuiexval->money;//期内还款金额
            }
            //=================放款统计===================
            $home['first_borrow'] = 0;
            $home['first_borrow_mon'] = 0;
            $first_orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select("id", "channel_id", "state", 'borrow_count', 'user_id', 'real_fee')->where("payment_at", '>=', $today)->where('borrow_count', '=', 0)->where("payment_at", '<=', $todayEnd)->get()->toArray();
            if(count($first_orders)){
                $home['first_borrow'] = count($first_orders);//首借人数
                foreach ($first_orders as $fikey => $fival){
                    $home['first_borrow_mon'] += $fival['real_fee'];//首借金额
                }
            }

            $home['reborrow'] = 0;
            $home['reborrow_mon'] = 0;
            $reborrow_orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select("id", "channel_id", "state", 'borrow_count', 'user_id', 'real_fee')->where("payment_at", '>=', $today)->where('borrow_count', '>', 0)->where("payment_at", '<=', $todayEnd)->get()->toArray();
            if(count($reborrow_orders)){
                $home['reborrow'] = count($reborrow_orders);//复借人数
                foreach ($reborrow_orders as $rekey => $reval){
                    $home['reborrow_mon'] += $reval['real_fee'];//复借金额
                }
            }

            //放款金额
            $home['todayPayMon'] = 0;
            $todayPayArr = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(real_fee) today_pay_fee')->whereBetween('payment_at', [$today, $todayEnd])->first();
            if ($todayPayArr['today_pay_fee']) {
                $home['todayPayMon'] = round($todayPayArr['today_pay_fee'] / 100, 1);
            }

            //放款人数
            $home['todayPayCount'] = 0;
            $todayPayCount = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) paymon_count')->whereBetween('payment_at', [$today, $todayEnd])->first();
            if ($todayPayCount['paymon_count']) {
                $home['todayPayCount'] = $todayPayCount['paymon_count'];
            }

            $payAndReportReport = PayAndRepay::withoutGlobalScopes()->where('tenant_id', $tenval)->where('now_date', $date)->first();
            if (!count($payAndReportReport)) {
                $payAndReportReport = new PayAndRepay();
                $payAndReportReport->now_date = $date;
                $payAndReportReport->tenant_id = $tenval;
            }

            $payAndReportReport->paycash = $home['todayPayMon'];
            $payAndReportReport->pay_channel_ids = '';
            $payAndReportReport->paycount = $home['todayPayCount'];
            $payAndReportReport->repaycash = $home['today_repay_arr'];
            $payAndReportReport->repay_channel_ids = '';
            $payAndReportReport->repaycount = $home['todayRepayPeople'];
            $payAndReportReport->wx_cash = $weixin;
            $payAndReportReport->zfb_cash = $zhifubao;

            $payAndReportReport->first_borrow = $home['first_borrow'];
            $payAndReportReport->first_borrow_mon = $home['first_borrow_mon'];
            $payAndReportReport->reborrow = $home['reborrow'];
            $payAndReportReport->reborrow_mon = $home['reborrow_mon'];

            $payAndReportReport->extend_count = $home['extend_count'];
            $payAndReportReport->extend_mon = $home['extend_mon'];
            $payAndReportReport->repay_ontime = $home['repay_ontime'];
            $payAndReportReport->repay_ontime_mon = $home['repay_ontime_mon'];
            $payAndReportReport->collect_count = $home['collect_count'];
            $payAndReportReport->collect_mon = $home['collect_mon'];
            $payAndReportReport->online_repay = $home['online_repay'];
            $payAndReportReport->offline_repay = $home['offline_repay'];

            //有数据才保存
            if ($payAndReportReport->paycash || $payAndReportReport->pay_channel_ids || $payAndReportReport->paycount || $payAndReportReport->repaycash || $payAndReportReport->repay_channel_ids || $payAndReportReport->repaycount || $payAndReportReport->wx_cash || $payAndReportReport->zfb_cash) {
                $payAndReportReport->save();
            }
        }
        echo 'success';
    }

    //还款短信提醒--加入定时任务
    public function repaysms()
    {
        //获取所有订单
        $orders = Order::with('user')->where('state', 2)
            ->where('payment_at', '<>', '')
            ->where('finished_at', '')
            ->where('repayment_at', '>=', date('Y-m-d').' 00:00:00')
            ->where('repayment_at', '<=', date('Y-m-d', strtotime('tomorrow')).' 23:59:59')
            ->get();

        //获取所有今天到期的用户的电话号码
        $today_should_repay_user_mobile = [];
        $tomorrow_should_repay_user_mobile = [];

        foreach ($orders as $key => $val){
            if(substr($val->repayment_at, 0, 10) == date('Y-m-d')){
                array_push($today_should_repay_user_mobile, $val->user->mobile);
            }elseif(substr($val->repayment_at, 0, 10) == date('Y-m-d', strtotime('tomorrow'))){
                array_push($tomorrow_should_repay_user_mobile, $val->user->mobile);
            }
        }
        
        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];
        //今日到期批量发送短信
        if(count($today_should_repay_user_mobile)){
            $today_params = [
                'form_params' => [
                    'number' => json_encode($today_should_repay_user_mobile),
                    'sign' => env('SIGN'),
                    'product_name' => $product_name,
                    'type' => 'today_repay'
                ]
            ];
            try {
                $send_url = env('OTHER_API') . '/api/tips/repay';
                $response = $this->guzzle($send_url, $today_params);
                $rcp = json_decode($response->getBody()->getContents(), true);
                @file_put_contents('../storage/jiancelogs/send_today_repay_msgtips_' . date('Ym') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($today_params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
                //更改订单状态
            } catch (\Exception $e) {
                @file_put_contents('../storage/jiancelogs/send_today_repay_msgtips_exc.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($today_params).'|exc='.$e->getMessage().PHP_EOL, FILE_APPEND);
            }
        }
        //明日到期批量发送短信
        if(count($tomorrow_should_repay_user_mobile)){
            //今日到期批量发送短信
            $tomorrow_params = [
                'form_params' => [
                    'number' => json_encode($tomorrow_should_repay_user_mobile),
                    'sign' => env('SIGN'),
                    'product_name' => $product_name,
                    'type' => 'tomorrow_repay'
                ]
            ];
            try {
                $send_url = env('OTHER_API') . '/api/tips/repay';
                $response = $this->guzzle($send_url, $tomorrow_params);
                $rcp = json_decode($response->getBody()->getContents(), true);
                @file_put_contents('../storage/jiancelogs/send_tomorrow_repay_msgtips_' . date('Ym') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($tomorrow_params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
                //更改订单状态
            } catch (\Exception $e) {
                @file_put_contents('../storage/jiancelogs/send_tomorrow_repay_msgtips_exc.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($tomorrow_params).'|exc='.$e->getMessage().PHP_EOL, FILE_APPEND);
            }
        }
    }

    //发送get方式的guzzle
    public function guzzle_get($url, $params)
    {
        $client = new GuzzleClient([
            // 超时
            'timeout' => 60.0,
        ]);
        return $client->request('GET', $url, $params);
    }

    //发送短信的guzzle
    public function guzzle($url, $params)
    {
        $client = new GuzzleClient([
            // 超时
            'timeout' => 60.0,
        ]);
        return $client->request('POST', $url, $params);
    }

    //排序判断-加入crontab
    public function judgement()
    {
        $start = date('Y-m-d H:i:s', time() - 86400 * 5);
        $end = date('Y-m-d H:i:s', time());
        $updated_at = date('Y-m-d H:i:s', time() - 20);
        //获得所有state为0的订单
        $orders = Order::with('channel')->where('state', 0)->where('updated_at', '<', $updated_at)->where('created_at', '>', $start)->where('created_at', '<', $end)->where('order_step', 3)->limit(30)->get();

        if (!count($orders)) return;
        //遍历机审
        foreach ($orders as $val) {
            $moxie = env('BSIGN');
            $oid = $val->id;
            //判断是不是需要参与机审
            try {
                $isauto = $val->channel->auto_audit_state;
            } catch (\Exception $ex) {
                @file_put_contents('../storage/logs/get_risk_auto_judge_audit_' . date('Ymd') . '.log', '||date=' . date('Y-m-d H:i:s') . '||oid=' . $oid . '||res=' . $ex->getMessage() . PHP_EOL, FILE_APPEND);
                continue;
            }

            switch ($isauto) {
                case 0:
                    continue;
                    break;
                case 1://自动审核
                    //防止重复提交数据
                    $reids_remark = $oid;
                    $redis_val = CommonController::comRedis('auto_risk_judge_' . $reids_remark, 600);
                    if (!$redis_val) {
                        continue;
                    }
                    //风控
                    $rsk = $this->get_risk_auto_judge($oid, $moxie);
                    @file_put_contents('../storage/logs/get_risk_auto_judge_1_' . date('Ymd') . '.log', json_encode($rsk) . '||date=' . date('Y-m-d H:i:s') . '||oid=' . $oid . PHP_EOL, FILE_APPEND);
                    //1：通过 2：不通过 3：人工复审
                    if (!$rsk['rspCode']) {//又返回值
                        if ($rsk['data']['state'] == 1) {//通过
                            $val->passtype = 5;
                            $val->state = 1;
                            $val->audited_at = date('Y-m-d H:i:s');
                        } elseif ($rsk['data']['state'] == 2) {//机审核不通过
                            $val->passtype = 6;
                            $val->state = -1;
                            $val->self_judge_msg .= '置信分不符合要求';
                        } elseif ($rsk['data']['state'] == 3) {//机审不通过的时候人工审核
                            $val->passtype = 7;
                            $val->state = 4;
                            $val->self_judge_msg .= '置信分人工复审';
                        }
                        $val->risk_score = isset($rsk['data']['score']) ? $rsk['data']['score'] : 0;
                        $val->save();
                    } else {//没有风控结果
                        $string = 'judgeCount_'.$oid;
                        $judgeCount = Redis::GET($string);
                        if($judgeCount < 4){
                            Redis::INCR($string);
                            continue;
                        }else{
                            $val->passtype = 6;
                            $val->state = -1;
                            $val->self_judge_msg .= '没有获得风控结果';
                        }
                    }
                    break;
                case 2://自动审核，人工复核
                    //防止重复提交数据
                    $reids_remark = $oid;
                    $redis_val = CommonController::comRedis('auto_risk_judge_' . $reids_remark, 600);
                    if (!$redis_val) {
                        continue;
                    }

                    //风控
                    $rsk = $this->get_risk_auto_judge($oid, $moxie);
                    @file_put_contents('../storage/logs/get_risk_auto_judge_2_' . date('Ymd') . '.log', json_encode($rsk) . '||date=' . date('Y-m-d H:i:s') . '||oid=' . $oid . PHP_EOL, FILE_APPEND);
                    //1：通过 2：不通过 3：人工复审
                    if (!$rsk['rspCode']) {//又返回值
                        if ($rsk['data']['state'] == 1) {//通过
                            $val->passtype = 1;
                            $val->state = 1;
                        } elseif ($rsk['data']['state'] == 2) {//机审核不通过
                            $val->passtype = 9;
                            $val->state = -1;
                            $val->self_judge_msg .= '置信分不符合要求';
                        } elseif ($rsk['data']['state'] == 3) {//机审不通过的人工审核
                            $val->passtype = 2;
                            $val->state = 4;
                            $val->self_judge_msg .= '置信分人工复审';
                        }
                        $val->risk_score = isset($rsk['data']['score']) ? $rsk['data']['score'] : 0;
                        $val->save();
                    } else {//没有风控结果
                        $string = 'judgeCount_'.$oid;
                        $judgeCount = Redis::GET($string);
                        if($judgeCount < 4){
                            Redis::INCR($string);
                            continue;
                        }else{
                            $val->passtype = 9;
                            $val->state = -1;
                            $val->self_judge_msg .= '没有获得风控结果';
                        }
                    }
                    break;
            }
        }
        echo 'success';
    }

    //后台获取审核失败的排序分
    public function get_fail_risk_score(request $request)
    {
        try{
            $rec = $request->all();
            $oid = $rec['oid'];
            $bsign = env('BSIGN');
            $res = $this->get_risk_auto_judge($oid, $bsign);
            if (!$res['rspCode']) {
                $order = Order::where('id', $oid)->first();
                $order->risk_score = $res['data']['score'] ? intval($res['data']['score']) : 0;
                $order->is_get_score = 2;
                $order->save();
                return ['code' => 0, 'score' => $order->risk_score];
            } else {
                return ['code' => -1, 'score' => $res['text']];
            }
        }catch (\Exception $ex){
            @file_put_contents('../storage/risk/hand_get_riskscore_err'.date('Ymd').'.log', date('Y-m-d H:i:s').'|err:'.$ex->getMessage().PHP_EOL, FILE_APPEND);
            return ['code' => -1, 'score' => $ex->getMessage()];
        }
    }

    //获得自定义风控的结果
    protected function get_risk_auto_judge($oid, $bsign)
    {
//        $oid = 1269;
        $order = Order::with('user')->where('id', $oid)->first();
        $channel_id = $order->channel_id;
        $uid = $order->user_id;

        //金蝉子扣费 扣风控的费用
        $chargeUrl = env('OTHER_API').'/api/sort/charge';
        $params = [
            'form_params' => [
                'sign' => env('SIGN'),
                'uid' => $uid,
            ]
        ];

        try{
            $gures = $this->guzzle($chargeUrl, $params);
            $response = json_decode($gures->getBody()->getContents(), true);
            @file_put_contents('../storage/risk/charge_risk_'.date('Ymd').'.log', date('Y-m-d H:i:s').'|post:'.json_encode($params).'|res:'.json_encode($response).PHP_EOL, FILE_APPEND);
            if($response['code']) return ['rspCode' => 4, 'text' => $response['text']];
        }catch (\Exception $ex){
            @file_put_contents('../storage/risk/charge_risk_err'.date('Ymd').'.log', date('Y-m-d H:i:s').'|err:'.$ex->getMessage().PHP_EOL, FILE_APPEND);
            return ['rspCode' => 4, 'text' => '扣费异常'];
        }

        //获取风控供应商
        $riskType = GlobalConfig::where('name', 'risktype')->value('value');
        if($riskType == 1){
            //指迷的风控结果
            $ActionPeopleController = new ActionPeopleController();
            $response = $ActionPeopleController->decisionMaking($order);
            if($response['code'] == -1){
                return ['rspCode' => 4, 'text' => $response['text']];
            }
        }elseif($riskType == 2){
            $MenghuaController = new MenghuaController();
            $response = $MenghuaController->queryScore($uid, $order);
            if($response['code'] == -1){
                return ['rspCode' => 4, 'text' => $response['text']];
            }
        }

        $decisionScore = $response['score'];//决策分数

        $risk_config = $this->getRiskScore($bsign, $channel_id);
        if($risk_config['code'] == -1){
            //返回人工复审的结果
            return ['rspCode' => 4, 'text' => '获取决策分数失败'];
        }
        //判断后返回状态和结果
        $ok_score = $risk_config['data']['ok_score'];
        $deny_score = $risk_config['data']['deny_score'];

        $response = [];
        $response['rspCode'] = 0;
        $response['data']['score'] = $decisionScore;
        if($decisionScore < $deny_score){
            $response['data']['state'] = 2;
        }elseif($decisionScore > $ok_score){
            $response['data']['state'] = 1;
        }else{
            $response['data']['state'] = 3;
        }

        return $response;

        //改版后暂时不用
        $userName = $order->user->verify_name;
        $orderId = $order->out_trade_no;
        $mobile = $order->user->mobile;
        $idNum = $order->user->verify_idcard_no;
        $gender = $order->user->verify_gender;
        $apply_time = $order->created_at->timestamp;
        $home_address = explode(' ', $order->user->reside_city);
        $province = isset($home_address[0]) ? $home_address[0] : '暂无';
        $city = isset($home_address[1]) ? $home_address[1] : '暂无';
        $liveAddr = isset($home_address[2]) ? $home_address[2] . $order->user->reside_address : $province . $city . $order->user->reside_address;
        $relatonA = $order->user->emergency_contact1_type;
        $relatonnameA = $order->user->emergency_contact1_name;
        $relatonphoneA = $order->user->emergency_contact1_mobile;
        $relatonB = $order->user->emergency_contact2_type;
        $relatonnameB = $order->user->emergency_contact2_name;
        $relatonphoneB = $order->user->emergency_contact2_mobile;

        $send_url = env('RISKDECISION') . "/easyuseapi/risk/decision/thridparty";

        $params = [
            'json' => [
                "channel_id" => $channel_id,
                "user_id" => $bsign,
                "userName" => $userName,
                "orderId" => $orderId,
                "mobile" => $mobile,
                "idNum" => $idNum,
                "gender" => $gender,
                "apply_time" => $apply_time,
                "operter_type" => '',
                "present" => [
                    "province" => $province,
                    "city" => $city,
                    "liveAddr" => $liveAddr
                ],
                "emergency_contacts" => [
                    [
                        "relation" => $relatonA,
                        "name" => $relatonnameA,
                        "phone" => $relatonphoneA
                    ],
                    [
                        "relation" => $relatonB,
                        "name" => $relatonnameB,
                        "phone" => $relatonphoneB
                    ]
                ]
            ],
            'headers' => [
                'ident' => 'production'
            ]
        ];
        try {
            @file_put_contents('../storage/logs/get_risk_auto_judge_params_' . date('Ymd') . '.log', 'start_date=' . date('Y-m-d H:i:s') . '||', FILE_APPEND);
            $ret = $this->guzzle($send_url, $params);
            $response = json_decode($ret->getBody()->getContents(), true);
            @file_put_contents('../storage/logs/get_risk_auto_judge_params_' . date('Ymd') . '.log', json_encode($params) . '|res=' . json_encode($response) . '||date=' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
            return $response;
        } catch (\Exception $exception) {
            @file_put_contents('../storage/logs/get_risk_auto_judge_exception_' . date('Ymd') . '.log', 'date=' . date('Y-m-d H:i:s') . '||info=' . $exception->getMessage() . PHP_EOL, FILE_APPEND);
        }
    }

    //获取风控系统的配置数据
    public function getRiskScore($bsign, $channel_id){
        $score_config_guid = RiskScoreChannel::where('user_id', $bsign)->where('channel_id', $channel_id)->value('score_config_guid');
        $risk_score_config = RiskScoreConfig::where('score_config_guid', $score_config_guid)->first()->toArray();
        if(!count($risk_score_config)){
            return ['code' => -1];
        }
        return ['code' => 0, 'data' => $risk_score_config];
    }

    //风控流程设置，判断续借的时候是不是还需要认证=======加入定时任务
    public function reverify()
    {
        //判断开关是不是开
        $users = User::with('channel.product')->where('finished_time', '<>', '')->get();

        if (!count($users)) return;
        foreach ($users as $val) {
            if ($val->channel->product->isopen == 2) {
                $days = $val->channel->product->freedays;
                $bool = strtotime($val['finished_time']) > time() - $days * 86400 ? true : false;
                if ($bool) {//没有过期
                    continue;
                } else {//过期
                    $val->carrier_ok = 0;//手机认证
                    $val->idcard_ok = 0;//身份证认证
                    $val->finished_time = '';
                    $val->save();
                }
            } else {
                $val->carrier_ok = 0;
                $val->idcard_ok = 0;
                $val->finished_time = '';
                $val->save();
            }
        }
    }

    //统计展期的数据=========加入定时任务 每天凌晨1点跑
    public function extendReport()
    {
        $date = date('Y-m-d', time());
        $start = $date . ' 0:0:0';
        $end = $date . ' 23:59:59';

        //获取所有的teannt_id
        $allTenantId = $this->getAllTenantId();
        if(!count($allTenantId)) die;

        foreach ($allTenantId as $tenval){
            $extend = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->where('created_at', '>', $start)->where('created_at', '<', $end)->get();
            $extend_people = DB::table('extend_offlines')->where('extend_offlines.tenant_id', $tenval)->join('orders', 'extend_offlines.order_id', '=', 'orders.id')->where('extend_offlines.created_at', '>', $start)->where('extend_offlines.created_at', '<', $end)->get();
            $extend_people = $this->forToArray($extend_people);//转数组
            $extend_num = count($this->assoc_unique($extend_people, 'user_id'));//去重

            $extend_report = ExtendReport::where('tenant_id', $tenval)->where('date_time', $date)->first();
            if (!count($extend_report)) {
                $extend_report = new ExtendReport();
                $extend_report->date_time = $date;
                $extend_report->tenant_id = $tenval;
            }
            $total = 0;
            $online = 0;
            $outline = 0;
            $wx = 0;
            $zfb = 0;

            foreach ($extend as $val) {
                $total += $val['money'];
                if (stripos($val->method, 'APP') !== false) {
                    $online += $val['money'];
                } else {
                    $outline += $val['money'];
                }

                if (stripos($val->method, '微信')) {
                    $wx += $val['money'];
                } elseif (stripos($val->method, '支付宝')) {
                    $zfb += $val['money'];
                }
            }

            $extend_report->total = $total;
            $extend_report->online = $online;
            $extend_report->outline = $outline;
            $extend_report->wxpay = $wx;
            $extend_report->zfbpay = $zfb;
            $extend_report->extend_num = $extend_num;

            if ($extend_report->total || $extend_report->online || $extend_report->outline || $extend_report->wxpay || $extend_report->zfbpay || $extend_report->extend_num) {
                $extend_report->save();
            }
        }
        echo 'success';
    }

    //按天统计产品数据 ======加入定时任务 凌晨1点前的时候执行
    public function product_report()
    {
//        $startTime = date('Y-m-d', time() - 3600 * 2). ' 00:00:00';
//        $endTime = date('Y-m-d', time() - 3600 * 2). ' 23:59:59';
        $today = date('Y-m-d', time());
        $startTime = $today . ' 00:00:00';
        $endTime = $today . ' 23:59:59';
        $pay_orders = Order::where([['payment_at', '>=', $startTime], ['payment_at', '<=', $endTime]])->get();
        $product = [];
        if (count($pay_orders)) {
            foreach ($pay_orders as $key => $pay_val) {
                if (!isset($product[$pay_val->product_id]['paycount'])) {
                    $product[$pay_val->product_id]['paycount'] = 0;
                }
                $product[$pay_val->product_id]['paycount'] += 1;
                if (!isset($product[$pay_val->product_id]['paymoney'])) {
                    $product[$pay_val->product_id]['paymoney'] = 0;
                }
                $product[$pay_val->product_id]['paymoney'] += $pay_val->real_fee;
            }
        }

        $todyTime = $today;
        foreach ($product as $product_id => $proval) {
            $productReport = ProductReport::where('product_id', $product_id)->where('date', $todyTime)->first();
            if (!count($productReport)) {
                $productReport = new ProductReport();
                $productReport->date = $todyTime;
                $productReport->product_id = $product_id;
            }

            $proval['paycount'] = $proval['paycount'] ?? 0;
            $proval['paymoney'] = $proval['paymoney'] ?? 0;
            $productReport->paycount = $proval['paycount'];
            $productReport->paymoney = $proval['paymoney'] / 100;

            if ($productReport->paycount || $productReport->paymoney || $productReport->repaycount || $productReport->repaymoney) {
                $productReport->save();
            }
        }
        //回款金额和回款笔数
        $meonthAgo = date('Y-m-d H:i:s', time() - 86400 * 100);
        $orderOfflneRepayArr = OrderOffline::select('order_id')->whereNotIn('method', ['免减'])->where('created_at', '>=', $meonthAgo)->get();//回款的订单id
        $extendOfflineRepayArr = ExtendOffline::select('order_id')->where('created_at', '>=', $meonthAgo)->get();//展期的订单ids
        $repay_order_ids = [];
        foreach ($orderOfflneRepayArr as $key => $orval){
            array_push($repay_order_ids, $orval->order_id);
        }
        foreach ($extendOfflineRepayArr as $key => $exval){
            array_push($repay_order_ids, $exval->order_id);
        }
        $orders = Order::with('orderoffline', 'extendoffline')->select('product_id', 'created_at','extend_time','finished_at',"id", "days" , "channel_id", "state", 'payment_at', 'total_fee', 'real_fee', 'repayment_fee', 'user_id', 'borrow_count')->whereIn('id', $repay_order_ids)->get();

        $productRepaymentData = [];
        foreach ($orders as $key => $val) {

            $product_id = $val['product_id'];
            $payment_at = substr($val['payment_at'], 0, 10);

            if (!isset($productRepaymentData[$product_id][$payment_at]['order_repay_mon'])) {
                $productRepaymentData[$product_id][$payment_at]['order_repay_mon'] = 0;
            }

            if (!isset($productRepaymentData[$product_id][$payment_at]['order_repay_count'])) {
                $productRepaymentData[$product_id][$payment_at]['order_repay_count'] = 0;
            }
            //统计所有此订单下的还款笔数和还款总金额
            $this_repay_money = 0;
            if (count($val->orderoffline)) {//展期为空，扣款不为空
                foreach ($val->orderoffline as $order_key => $order_val) {
                    if ($order_val['method'] != '免减') {
                        $this_repay_money += $order_val['money'];
                    }
                }
            }

            //统计所有此订单下的展期笔数和展期总金
            if (count($val->extendoffline)) {
                foreach ($val->extendoffline as $extend_key => $extend_val) {
                   $this_repay_money += $extend_val['money'];
                }
            }

            $productRepaymentData[$product_id][$payment_at]['order_repay_count'] ++;

            $productRepaymentData[$product_id][$payment_at]['order_repay_mon'] += $this_repay_money;//回款金额
        }

        //放款那一天的回款率和回款金额以及回款笔数数
        if(count($productRepaymentData)){
            foreach ($productRepaymentData as $product_id => $pay_val) {
                foreach ($pay_val as $payment_at => $repay) {
                    $product_data_report = ProductReport::where("date", $payment_at)->where("product_id", $product_id)->first();
                    if (!count($product_data_report)) {
                        $product_data_report = new ProductReport();
                        $product_data_report->product_id = $product_id;
                        $product_data_report->created_at = date("Y-m-d H:i:s");
                        $product_data_report->date = $payment_at;
                    }
                    $product_data_report->repaycount = $repay['order_repay_count'];
                    $product_data_report->repaymoney = $repay['order_repay_mon'];

                    $product_data_report->save();
                }
            }
        }
        echo 'success';
    }

    //二维数组去重
    protected function assoc_unique($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        sort($arr); //sort函数对数组进行排序
        return $arr;
    }

    //获取缓存文件的数据
    protected function product_config()
    {
        $product_config = new ProductFlockController();
        $product_base = $product_config->read_file();
        return $product_base;
    }

    //获取每日明细数据的报表
    public function general_report()
    {
        $date = date('Y-m-d');
//        $date = date('Y-m-d', strtotime('-9 day'));
        $today_start = $date . ' 00:00:00';
        $today_end = $date . ' 23:59:59';

        $today_start_time = strtotime($today_start);
        $today_end_time = strtotime($today_end);

        //获取所有的teannt_id
        $allTenantId = $this->getAllTenantId();
        if(!count($allTenantId)) die;

        foreach ($allTenantId as $tenval){
            $todayRegisterCount = User::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(id) user_cnt')->whereBetween('created_at', [$today_start, $today_end])->first();//注册人数
            $general['register_cnt'] = 0;
            if ($todayRegisterCount['user_cnt']) {
                $general['register_cnt'] = $todayRegisterCount['user_cnt'];//注册人数
            }
            //当日完成成认证的用户数
            $todayVerifyAllCount = User::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(id) verify_cnt')
                ->whereBetween('created_at', [$today_start, $today_end])
                ->where('idcard_ok', 1)
                ->where('carrier_ok', 1)
                ->where('emergency_contact_ok', 1)
                ->where('verify_pay_ok', 1)
                ->first();//认证人数
            $general['today_verify_count'] = 0;
            if ($todayVerifyAllCount['verify_cnt']) {
                $general['today_verify_count'] = $todayVerifyAllCount['verify_cnt'];
            }
            //uv统计
    //        $general['uv'] = $this->get_uv_stastic();
            //提交人数
            $todayCountArr = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(id) borrow_cnt')->whereBetween('created_at', [$today_start, $today_end])->first();//借款申请数
            $general['borrow_cnt'] = 0;
            if ($todayCountArr['borrow_cnt']) {
                $general['borrow_cnt'] = $todayCountArr['borrow_cnt'];
            }
            //首签人数
            $today_first_people_orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->where('borrow_count', 0)->whereBetween('confirm_date', [$today_start, $today_end])->count();
            $general['first_borrow_people'] = $today_first_people_orders;

            //首签金额
            $today_first_people_orders_arr = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(real_fee) first_borrow_people')->where('borrow_count', 0)->whereBetween('confirm_date', [$today_start, $today_end])->first();
            $general['first_borrow_people_arr'] = 0;
            if ($today_first_people_orders_arr['first_borrow_people']) {
                $general['first_borrow_people_arr'] = $today_first_people_orders_arr['first_borrow_people'];
            }

            //签约率 =  首借人数 / 注册人数
            $general['down_rate'] = 0;
            if ($general['register_cnt']) {
                $general['down_rate'] = round($general['first_borrow_people'] / $general['register_cnt'], 2);
            }

            //复签人数
            $reborrow_people = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->whereBetween('confirm_date', [$today_start, $today_end])->where('borrow_count', '>', 0)->count();
            $general['reborrow_cnt'] = $reborrow_people;

            //复签金额
            $reborrow_arr = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(real_fee) reborrow_arr')->whereBetween('confirm_date', [$today_start, $today_end])->where('borrow_count', '>', 0)->first();
            $general['reborrow_arr'] = 0;
            if ($reborrow_arr['reborrow_arr']) {
                $general['reborrow_arr'] = $reborrow_arr['reborrow_arr'];
            }

            //合计签约金额
            $general['total_mon'] = $general['reborrow_arr'] + $general['first_borrow_people_arr'];

            //展期人数
            $extendPeopleCount = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(order_id)) today_extend_people')->where('created_at', '>=', $today_start)->first();
            $general['extend_cnt'] = 0;
            if ($extendPeopleCount['today_extend_people']) {
                $general['extend_cnt'] = $extendPeopleCount['today_extend_people'];
            }

            //展期金额
            $extned_mon = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) as ext_mon')->whereBetween('created_at', [$today_start, $today_end])->first();
            $general['extend_mon'] = 0;
            if ($extned_mon['ext_mon']) {
                $general['extend_mon'] = $extned_mon['ext_mon'];
            }

            //应收金额
            $all['allShouldRepayMon'] = 0;
            $allShouldRepayOrders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->whereBetween('repayment_at', [$today_start, $today_end])->where('repayment_at', '<>', '')->get();
            foreach ($allShouldRepayOrders as $key => $val) {
                $payment_at = $val->payment_at;
                $finished_at = $val->finished_at;
                $default_interest = $val->default_interest;
                $real_fee = $val->real_fee;

                $httpCommon = new CommonController();
                $interest = $httpCommon->interest($finished_at, $payment_at, $default_interest, $real_fee);

                $all['allShouldRepayMon'] += $real_fee + $interest;
            }
            $general['should_repay_mon'] = $all['allShouldRepayMon'];

            //回款金额
            $todayRepayArr = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) today_repay_fee')->whereNotIn('method', ['免减'])->whereBetween('created_at', [$today_start, $today_end])->first();//回款金额
            $extendArr = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) today_extendarr')->whereBetween('created_at', [$today_start, $today_end])->first();//今日展期的金额
            $general['today_should_repay_mon'] = $todayRepayArr['today_repay_fee'] + $extendArr['today_extendarr'];

            //到期人数 没有展期的到期人数 + 展期的到期人数
            $zuoyibai = date('Y-m-d H:i:s', time() - 300 * 86400);
            $todayExtendRepayPeople = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id', 'user_id', 'once_repayment_at')->where('payment_at', '>=', $zuoyibai)->where('once_repayment_at', '<>', '')->get();

            $general['today_should_repay_cnt'] = 0;
            $today_orders_ids = [];
            foreach ($todayExtendRepayPeople as $yikey => $yival){
                $once_time_arr = explode(',', $yival->once_repayment_at);
                foreach ($once_time_arr as $onceval){
                    if($onceval > $today_start_time && $onceval < $today_end_time){
                        array_push($today_orders_ids, $yival->id);
                        break;
                    }
                }
            }

            $today_should_order = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) should_repay_people')->whereIn('id', $today_orders_ids)->first();
            if($today_should_order['should_repay_people']){
                $general['today_should_repay_cnt'] = $today_should_order['should_repay_people'];
            }

            //未履约人数
            $todayNotRepayPeople = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$today_start, $today_end])->where('finished_at', '=', '')->get();
            $todayNotRepayPeopleArr = [];
            foreach ($todayNotRepayPeople as $nokey => $noval){
                array_push($todayNotRepayPeopleArr, $noval->id);
            }

            $today_notrepay_order = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) today_notrepay_people')->whereIn('id', $todayNotRepayPeopleArr)->first();
            $general['today_norepay_people'] = 0;
            if($today_notrepay_order['today_notrepay_people']){
                $general['today_norepay_people'] = $today_notrepay_order['today_notrepay_people'];
            }

            //提前还款 = 今日提前还款
            $todayPreRepayPeople = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->where('repayment_at', '>=', $today_end)->whereBetween('finished_at', [$today_start, $today_end])->get();
            $todayPreRepayPeopleArr = [];
            foreach ($todayPreRepayPeople as $preval){
                array_push($todayPreRepayPeopleArr, $preval->id);
            }

            $todayPreOrders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) today_prerepay_people')->whereIn('id', $todayPreRepayPeopleArr)->first();
            $general['pre_repay_people'] = 0;
            if($todayPreOrders['today_prerepay_people']){
                $general['pre_repay_people'] = $todayPreOrders['today_prerepay_people'];
            }

            //回款率  （回款人数 - 提前还款）/ 到期人数
            //回款人数
    //        $allNatialRepayMon = OrderOffline::select('order_id')->whereNotIn('method', ['免减'])->whereBetween('created_at', [$today_start, $today_end])->get();//回款金额
    //        $allNatialExtendMon = ExtendOffline::select('order_id')->whereBetween('created_at', [$today_start, $today_end])->get();//展期的金额
    //        $allRepayOrderIds = [];
    //        foreach ($allNatialRepayMon as $key => $val) {
    //            if (!in_array($val->order_id, $allRepayOrderIds)) {
    //                array_push($allRepayOrderIds, $val->order_id);
    //            }
    //        }
    //        foreach ($allNatialExtendMon as $key => $val) {
    //            if (!in_array($val->order_id, $allRepayOrderIds)) {
    //                array_push($allRepayOrderIds, $val->order_id);
    //            }
    //        }
    //        $payedMonOrders = Order::selectRaw('count(distinct(user_id)) today_repay_people')->whereIn('id', $allRepayOrderIds)->first();
    //        $general['todayRepayPeoples'] = 0;
    //        if ($payedMonOrders['today_repay_people']) {
    //            $general['todayRepayPeoples'] = $payedMonOrders['today_repay_people'];
    //        }

            //回款率
    //        $general['repay_rate'] = 0;
    //        if ($general['today_should_repay_cnt']) {
    //            $repay_rate = ($general['todayRepayPeoples'] - $general['pre_repay_people']) / $general['today_should_repay_cnt'];
    //            $general['repay_rate'] = round($repay_rate, 2);
    //        }

            //逾期率
            $general['over_repay_rate'] = 0;
            if ($general['today_should_repay_cnt']) {
                $repay_rate = $general['today_norepay_people'] / $general['today_should_repay_cnt'];
                $general['over_repay_rate'] = round($repay_rate, 2);
            }

            $genersl_report = GeneralReport::withoutGlobalScopes()->where('tenant_id', $tenval)->where('date', $date)->first();
            if (!count($genersl_report)) {
                $genersl_report = new GeneralReport();
                $genersl_report->date = $date;
                $genersl_report->tenant_id = $tenval;
            }
//            $genersl_report->uv = $general['uv'];
            $genersl_report->register_cnt = $general['register_cnt'];//注册人数
            $genersl_report->today_verify_count = $general['today_verify_count'];//认证人数
            $genersl_report->borrow_cnt = $general['borrow_cnt'];//申请人数
            $genersl_report->first_borrow_people = $general['first_borrow_people'];//首借人数
            $genersl_report->first_borrow_people_arr = $general['first_borrow_people_arr'];//首借金额
            $genersl_report->down_rate = $general['down_rate'];//下款率
            $genersl_report->reborrow_cnt = $general['reborrow_cnt'];//复借人数
            $genersl_report->reborrow_arr = $general['reborrow_arr'];//复借金额
            $genersl_report->total_mon = $general['total_mon'];//合计借出
            $genersl_report->extend_cnt = $general['extend_cnt'];//展期人数
            $genersl_report->extend_mon = $general['extend_mon'];//展期金额
            $genersl_report->should_repay_mon = $general['should_repay_mon'];//应收金额
            $genersl_report->today_should_repay_mon = $general['today_should_repay_mon'];//回款金额
            $genersl_report->today_should_repay_cnt = $general['today_should_repay_cnt'];//到期人数
            $genersl_report->today_norepay_people = $general['today_norepay_people'];//未还人数
            $genersl_report->pre_repay_people = $general['pre_repay_people'];//提前还款人数
            $genersl_report->over_repay_rate = $general['over_repay_rate'];//逾期率

            $genersl_report->save();

        }
        echo 'success';
    }

    //对象转数组
    protected function forToArray($e)
    {
        $arr = [];
        foreach ($e as $key => $val) {
            $arr[] = $this->objectToArray($val);
        }
        return $arr;
    }

    //对象转数组
    protected function objectToArray($e)
    {
        $e = (array)$e;
        foreach ($e as $k => $v) {
            if (gettype($v) == 'resource') return;
            if (gettype($v) == 'object' || gettype($v) == 'array')
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }

    //当日到期订单应还金额之和
    protected function today_should_repay()
    {
        $date = date('Y-m-d');
        $today_start = $date . ' 00:00:00';
        $today_end = $date . ' 23:59:59';

        $order = Order::whereBetween('repayment_at', [$today_start, $today_end])->get();
        $total_repay_mon = 0;
        foreach ($order as $val) {
            $repayment_at = $val->repayment_at;
            $payment_at = $val->payment_at;
            $repayment_fee = $val->repayment_fee;
            #计算利息
            $interest_total = ($val->interest) * ($val->real_fee) * ((strtotime(substr($repayment_at, 0, 10)) - strtotime(substr($payment_at, 0, 10))) / 86400) / 10000;
            #计算展期费 因为是第一次扣款,所以展期费是0
            $default_interest_total = 0;
            #计算总费用
            $AMT = $val->total_fee + $interest_total + $default_interest_total - $repayment_fee;
            $total_repay_mon += $AMT;
        }
        return $total_repay_mon;
    }

    //uv统计量
    protected function get_uv_stastic()
    {
        $uv_total = 0;
        try {
            //获取uv数据并且做统计
            $uv_result = $this->getUvStastic();
            if ($uv_result['rspCode'] == 0) {
                $date = date('Ymd');
                foreach ($uv_result['data'] as $key => $uval) {
                    if ($uval['trackdate'] == $date) {
                        $uv_total += $uval['visitors'];
                    }
                }
            }
        } catch (\Exception $ex) {
            @file_put_contents('../storage/logs/cron_channel_report' . date('Ymd') . '.log', $ex->getMessage() . '||line=' . $ex->getLine() . '||date=' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
        }
        return $uv_total;
    }
    //逾期客户自动加入黑名单, 每天凌晨执行一次
    public function join_black(){
        $order_arr = [];
        $user_ids = [];
        $mobiles = [];
        $orders = Order::with(['user' => function($query){
            $query->select('id', 'mobile', 'verify_name', 'verify_idcard_no');
        }])->select('id','user_id')->where('finished_at', ' ')->where('repayment_at', '<>', ' ')->where('repayment_at', '<=', date('Y-m-d').' 00:00:00')->where('repayment_at', '>=', date('Y-m-d H:i:s', strtotime('yesterday')))->get();
        foreach ($orders as $key => $val){
            $one_blk = [
              'user_id' => env('BSIGN'),
              'name' => $val->user->verify_name,
              'mobile' => $val->user->mobile,
              'id_no' => $val->user->verify_idcard_no,
              'class_name' => '逾期客户'
            ];
            array_push($order_arr, $one_blk);
            array_push($user_ids, $val->user->id);
            array_push($mobiles, $val->user->mobile);
        }
        $common_controller = new AdminCommonController();
        $common_controller->over_auto_join_black($order_arr, $user_ids, $mobiles);
    }
    //把用户的认证状态传送到分控服务器
    public function transfer_user_state_torisk(){
        $users = User::with(['order' => function($query){
            $query->select('id', 'user_id', 'state', 'created_at')->orderBy('id', 'desc');
        }])->select('id', 'verify_name', 'mobile', 'verify_idcard_no', 'idcard_ok', 'alive_ok')->get();
        $risk_url = env('RISKDECISION').'/risk/Data/SaveBorrowUser';
        //写入user表
        $transfer_obj = new TransferController();
        $product_base = $transfer_obj->product_config();
        $appname = $product_base['appname'];
        foreach ($users as $key => $val){
            $order_no = '';
            $order_state = 0;
            if(count($val->order) > 0){
                $order_no = $val->order[0]['id'];
                $order_state = $val->order['0']['state'];
            }
            $is_realname = 0;
            if($val->idcard_ok == 1 && $val->alive_ok == 1){
                $is_realname = 1;
            }
            $params = [
                'json' => [
                    'user_id' => env('BSIGN'),
                    'user_name' => $appname,
                    'mobile' => $val->mobile,
                    'id_no' => $val->verify_idcard_no,
                    'name' => $val->verify_name,
                    'order_no' => $order_no,
                    'borrow_state' => $order_state,
                    'is_realname' => $is_realname,
                    'apply_time' => $val->order->created_at->timestamp

                ]
            ];
            $res = $this->guzzle($risk_url, $params);
            $response = json_decode($res->getBody()->getContents(), true);
            @file_put_contents('../storage/jiancelogs/transfer_userstate_torisk'.date('Ym').'.log', 'data='.date('Y-m-d H:i:s').'|res='.json_encode($response).PHP_EOL, FILE_APPEND);
        }

    }
    //传送风控的数据到金蝉子系统做数据统计
    public function risk_statistics(){
        $time = time() - 3600 * 2;//两个小时以前的
        $start = date('Y-m-d', $time) . ' 00:00:00';
        $end = date('Y-m-d', $time) . ' 23:59:59';

        $consume = new Consume();
        $verify_num = $consume->where('consume_type', 1)->whereBetween('consume_time', [$start, $end])->count();//实名认证的人数
        $mobile_num = $consume->where('consume_type', 8)->whereBetween('consume_time', [$start, $end])->count();//手机认证的人数
        $bankcard_num = $consume->where('consume_type', 3)->whereBetween('consume_time', [$start, $end])->count();//银行卡认证的人数
        $access_num = $consume->where('consume_type', 9)->whereBetween('consume_time', [$start, $end])->count();//准入认证的人数
        $confidence_num = $consume->where('consume_type', 5)->whereBetween('consume_time', [$start, $end])->count();//置信认证的人数
        $message_num = $consume->where('consume_type', 6)->whereBetween('consume_time', [$start, $end])->count();//短信认证的人数
        $risk = $consume->selectRaw('sum(consume_fee) risk_fee')->whereBetween('consume_time', [$start, $end])->first();//风控费
        $risk_fee = $risk->risk_fee ? $risk->risk_fee : 0;
        $params = [
            'form_params' => [
                'sign' => env('SIGN'),
                'verify' => $verify_num,
                'mobile' => $mobile_num,
                'bankcard' => $bankcard_num,
                'access' => $access_num,
                'confidence' => $confidence_num,
                'message' => $message_num,
                'risk' => $risk_fee
            ]
        ];
        $send_url = env('OTHER_API') . '/api/risk/stastistics';
        $res = $this->guzzle($send_url, $params);
        $response = json_decode($res->getBody()->getContents(), true);
        return $response;
    }
    //到期统计, 加入定时任务
    public function mature(){
        $date = date('Y-m-d');
        $start = $date.' 00:00:00';
        $end = $date. ' 23:59:59';

        //获取所有的teannt_id
        $allTenantId = $this->getAllTenantId();
        if(!count($allTenantId)) die;

        foreach ($allTenantId as $tenval){
            //到期人数 == 单期人数 + 分期人数
            $danqi_mature_count = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$start, $end])->get();
            $daoqirenshu_ids = [];
            foreach ($danqi_mature_count as $dankey => $danval){
                array_push($daoqirenshu_ids, $danval->id);
            }
    //        $fenqi_mature_count = DivideOrder::select('order_id')->whereBetween('repay_time', [$start, $end])->get();
    //        foreach ($fenqi_mature_count as $fenkey => $fenval){
    //            array_push($daoqirenshu_ids, $fenval->order_id);
    //        }
            $daoqiorders_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) mature_count')->whereIn('id', $daoqirenshu_ids)->first();
            $home['mature_count'] = 0;
            if($daoqiorders_obj['mature_count']){
                $home['mature_count'] = $daoqiorders_obj['mature_count'];
            }

            //首借到期人数
            //首借到期人数 == 单期首借人数 + 分期首借人数
            $shoujie_danqi_mature_count = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$start, $end])->where('borrow_count', 0)->get();
            $shoujie_daoqirenshu_ids = [];
            foreach ($shoujie_danqi_mature_count as $soudankey => $soudanval){
                array_push($shoujie_daoqirenshu_ids, $soudanval->id);
            }
    //        $shoujie_fenqi_mature_count = DivideOrder::select('order_id')->whereBetween('repay_time', [$start, $end])->where('borrow_count', 0)->get();
    //        foreach ($shoujie_fenqi_mature_count as $soufenkey => $soufenval){
    //            array_push($shoujie_daoqirenshu_ids, $soufenval->order_id);
    //        }
            $shoudaoqiorders_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) first_count')->whereIn('id', $shoujie_daoqirenshu_ids)->first();
            $home['first_count'] = 0;
            if($shoudaoqiorders_obj['first_count']){
                $home['first_count'] = $shoudaoqiorders_obj['first_count'];
            }

            //首借到期回款
            $orderlog = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) first_money')->whereIn('order_id', $shoujie_daoqirenshu_ids)->whereNotIn('method', ['免减'])->first();
            $home['first_money'] = 0;
            if($orderlog['first_money']){
                $home['first_money'] += $orderlog['first_money'];
            }
            $extendlog = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) first_money')->whereIn('order_id', $shoujie_daoqirenshu_ids)->first();
            if($extendlog['first_money']){
                $home['first_money'] += $extendlog['first_money'];
            }

            //首借逾期率 == 首借到期未还人数/首借到期人数
            //首借到期未还人数
            $shoujiedaoqi_weihuan_renshu = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$start, $end])->where('borrow_count', 0)->where('finished_at', '')->get();
            $shoujiedao_weihuan_ids = [];
            foreach ($shoujiedaoqi_weihuan_renshu as $daoqiweikey => $daoqiweival){
                array_push($shoujiedao_weihuan_ids, $daoqiweival->id);
            }
    //        $shoujiefenqi_weihuan_renshu = DivideOrder::select('order_id')->whereBetween('repay_time', [$start, $end])->where('borrow_count', 0)->where('finished_at', '')->get();
    //        foreach($shoujiefenqi_weihuan_renshu as $fendaoqiweikey => $fendaoqiweival){
    //            array_push($shoujiedao_weihuan_ids, $fendaoqiweival->order_id);
    //        }
            $shoudaoqiorders_weihuan_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) first_weihuan_count')->whereIn('id', $shoujiedao_weihuan_ids)->first();
            $home['first_weihuan_count'] = 0;
            if($shoudaoqiorders_weihuan_obj['first_weihuan_count']){
                $home['first_weihuan_count'] = $shoudaoqiorders_weihuan_obj['first_weihuan_count'];
            }
            //首借逾期率 == 首借到期未还人数/首借到期人数
            $home['first_rate'] = 0;
            if($home['first_count']){
                $home['first_rate'] = $home['first_weihuan_count']/$home['first_count'];
            }

            //=======================复借到期==============
            //复借到期人数
            //复借到期人数 == 单期首借人数 + 分期首借人数
            $fujie_danqi_mature_count = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$start, $end])->where('borrow_count', '>', 0)->get();
            $fujie_daoqirenshu_ids = [];
            foreach ($fujie_danqi_mature_count as $fudankey => $fudanval){
                array_push($fujie_daoqirenshu_ids, $fudanval->id);
            }
    //        $fujie_fenqi_mature_count = DivideOrder::select('order_id')->whereBetween('repay_time', [$start, $end])->where('borrow_count', '>', 0)->get();
    //        foreach ($fujie_fenqi_mature_count as $fufenkey => $fufenval){
    //            array_push($fujie_daoqirenshu_ids, $fufenval->order_id);
    //        }
            $fudaoqiorders_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) reborrow_count')->whereIn('id', $fujie_daoqirenshu_ids)->first();
            $home['reborrow_count'] = 0;
            if($fudaoqiorders_obj['reborrow_count']){
                $home['reborrow_count'] = $fudaoqiorders_obj['reborrow_count'];
            }

            //复借到期回款
            $fuorderlog = OrderOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) reborrow_money')->whereIn('order_id', $fujie_daoqirenshu_ids)->whereNotIn('method', ['免减'])->first();
            $home['reborrow_money'] = 0;
            if($fuorderlog['reborrow_money']){
                $home['reborrow_money'] += $fuorderlog['reborrow_money'];
            }
            $fuextendlog = ExtendOffline::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('sum(money) reborrow_money')->whereIn('order_id', $fujie_daoqirenshu_ids)->first();
            if($fuextendlog['reborrow_money']){
                $home['reborrow_money'] += $fuextendlog['reborrow_money'];
            }

            //复借逾期率 == 复借到期未还人数/复借到期人数
            //复借到期未还人数
            $fujiedaoqi_weihuan_renshu = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->select('id')->whereBetween('repayment_at', [$start, $end])->where('borrow_count', '>', 0)->where('finished_at', '')->get();
            $fujiedao_weihuan_ids = [];
            foreach ($fujiedaoqi_weihuan_renshu as $fudaoqiweikey => $fudaoqiweival){
                array_push($fujiedao_weihuan_ids, $fudaoqiweival->id);
            }
    //        $fujiefenqi_weihuan_renshu = DivideOrder::select('order_id')->whereBetween('repay_time', [$start, $end])->where('borrow_count', '>', 0)->where('finished_at', '')->get();
    //        foreach($fujiefenqi_weihuan_renshu as $fufendaoqiweikey => $fufendaoqiweival){
    //            array_push($fujiedao_weihuan_ids, $fufendaoqiweival->order_id);
    //        }
            $fudaoqiorders_weihuan_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) fu_first_weihuan_count')->whereIn('id', $fujiedao_weihuan_ids)->first();
            $home['reborrow_weihuan_count'] = 0;
            if($fudaoqiorders_weihuan_obj['fu_first_weihuan_count']){
                $home['reborrow_weihuan_count'] = $fudaoqiorders_weihuan_obj['fu_first_weihuan_count'];
            }
            //复借逾期率 == 复借到期未还人数/复借到期人数
            $home['reborrow_rate'] = 0;
            if($home['reborrow_count']){
                $home['reborrow_rate'] = $home['reborrow_weihuan_count']/$home['reborrow_count'];
            }

            //展期到期
            $extend_orders_obj = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->selectRaw('count(distinct(user_id)) extend_mature')->where('extend_time', '<>', '')->whereBetween('repayment_at', [$start, $end])->first();
            $home['extend_mature'] = 0;
            if($extend_orders_obj['extend_mature']){
                $home['extend_mature'] = $extend_orders_obj['extend_mature'];
            }

            $mature = Mature::where('tenant_id', $tenval)->where('date', $date)->first();
            if(!count($mature)){
                $mature = new Mature();
                $mature->date = $date;
                $mature->tenant_id = $tenval;
            }
            //有值则生成，没有值则不生成
            foreach ($home as $hval){
                if($hval){
                    $mature->mature_count = $home['mature_count'];
                    $mature->first_count = $home['first_count'];
                    $mature->first_money = $home['first_money'];
                    $mature->first_weihuan_count = $home['first_weihuan_count'];
                    $mature->first_rate = $home['first_rate'];
                    $mature->reborrow_count = $home['reborrow_count'];
                    $mature->reborrow_money = $home['reborrow_money'];
                    $mature->reborrow_weihuan_count = $home['reborrow_weihuan_count'];
                    $mature->reborrow_rate = $home['reborrow_rate'];
                    $mature->extend_mature = $home['extend_mature'];
                    $mature->save();
                    break;
                }
            }
        }
        echo 'success';
    }

    //不良资产统计
    public function collector(){
        $date = date('Y-m-d');

        //获取所有的teannt_id
        $allTenantId = $this->getAllTenantId();
        if(!count($allTenantId)) die;

        foreach ($allTenantId as $tenval){
            $orders = Order::withoutGlobalScopes()->where('tenant_id', $tenval)->with('extendoffline', 'orderoffline')->where('collector_id', '>', 0)->where('repayment_fee', '<>', '')->where('finished_at', '<>', '')->get();
            if(!count($orders)) die;
            //清空数据
            foreach ($orders as $okey => $oval){
                $collector = $oval['collector_id'];
                $initCollector = CollectorReport::where('tenant_id', $tenval)->where('collector', $collector)->where('date', $date)->first();
                if(count($collector)){
                    $initCollector->backpeople = 0;
                    $initCollector->backmoney = 0;
                    $initCollector->online = 0;
                    $initCollector->wx = 0;
                    $initCollector->zfb = 0;
                    $initCollector->freemoney = 0;
                }
            }
           
            foreach ($orders as $okey => $oval){
                $collector = $oval['collector_id'];
                $extendoffline = $orders->extendoffline;
                $orderoffline = $orders->orderoffline;
                $collector = CollectorReport::where('tenant_id', $tenval)->where('collector', $collector)->where('date', $date)->first();
                if(!count($collector)){
                    $collector = new CollectorReport();
                    $collector->collector = $collector;
                    $collector->date = $date;
                    $collector->tenant_id = $tenval;
                }
                $collector->backpeople += 1;
                //计算展期费用
                if(count($extendoffline)){
                    foreach ($extendoffline as $exkey => $exval){
                        $exdate = substr($exval['created_at'], 0, 10);
                        $exmethod = $exval['method'];

                        if($exdate == $date){
                            //还款金额
                            $collector->backmoney += $exval['money'];
                            if($exmethod == 'APP线上展期'){
                                $collector->online += $exval['money'];
                            }elseif($exmethod == '线下微信'){
                                $collector->wx += $exval['money'];
                            }elseif($exmethod == '线下支付宝'){
                                $collector->zfb += $exval['money'];
                            }
                        }

                    }
                }
                //计算还款费用
                if(count($orderoffline)){
                    foreach ($orderoffline as $orkey => $orval){
                        $ordate = substr($orval['created_at'], 0, 10);
                        $ormethod = $orval['method'];

                        if($ordate == $date){
                            //还款总金额
                            if($ormethod != '免减'){
                                $collector->backmoney += $orval['money'];
                            }
                            if($ormethod == '用户主动还款'){
                                $collector->online += $orval['money'];
                            }elseif($ormethod == '线下微信'){
                                $collector->wx += $orval['money'];
                            }elseif($ormethod == '线下支付宝'){
                                $collector->zfb += $orval['money'];
                            }elseif($ormethod == '免减'){
                                $collector->freemoney += $orval['money'];
                            }
                        }
                    }
                }
                $collector->save();
            }
        }
        echo 'success';
    }

    //每天凌晨改变订单的状态，检测是不是已逾期
    public function overDateOrderChangeState(){
        $orders = Order::withoutGlobalScopes()
            ->where('finished_at', '')
            ->where('confirm_date', '<>', '')
            ->where('initiate_date', '<>', '')
            ->where('repayment_at', '<>', '')
            ->where('repayment_at', '<', date('Y-m-d').' 00:00:00')
            ->update(['state' => -3]);
//            ->get();

        echo 'success';
    }

    //定时任务判断是否过期
    public function overConfirTime(){
        $orders = Order::withoutGlobalScopes()
            ->where('over_date', '')
            ->where('confirm_date', '')
            ->where('initiate_date', '<>', '')
            ->get();

        foreach ($orders as $val){
            if(strtotime(date('Y-m-d H:i:s')) - strtotime($val['initiate_date']) > 3600 * 24){
                $val->over_date = date('Y-m-d H:i:s');
                $val->state = 6;
                $val->save();
            }
        }

        echo 'success';
    }
}